﻿using BuyWithoutLoseMoney.Core.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System;
using BuyWithoutLoseMoney;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    ///权限
    /// </summary>
    [Area("admin")]
    public class BaseAdminController : Controller
    {
        private readonly BuyWithoutLoseMoneyDBContext _appDbcontext;
        public BaseAdminController(BuyWithoutLoseMoneyDBContext appDbcontext)
        {
            _appDbcontext = appDbcontext;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string cookieName = Request.Cookies["setCookieExpires"];
            base.OnActionExecuting(context);
            var u = _appDbcontext.LoginUsers.Include(x=>x.Role).ThenInclude(x=>x.Permission).Where(x => x.LoginName == cookieName).FirstOrDefault();//获取用户信息
            if (u != null)
            {
                List<Permission> pList = new List<Permission>();
                foreach (var item in u.Role)//将权限添加到集合当中
                {
                    pList.AddRange(item.Permission);
                }
                var controllerName = context.RouteData.Values["controller"].ToString();//获取控制区名称
                var actionName = context.RouteData.Values["action"].ToString();//获取动作方法
                bool hasPermission = pList.Any(p => p.ControllerName.ToLower().Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && p.ActionName.ToLower()
                .Equals(actionName, StringComparison.CurrentCultureIgnoreCase));//用于检查用户是否有权限执行指定的控制器和操作
                if (!hasPermission)//否则返回未授权页面
                {
                    context.Result = Unauthorized();
                }
            }
        }
        public new ActionResult Unauthorized()
        {
            return View("/views/error/unauthorized.cshtml");
        }
    }
}
